/*
 * Copyright (c) 2012-2013, Yunnan Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package net.jeeshop.web.action.phone;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuanxin.service.biz.schuserbase.appobject.OrganMemberEntityAO;
import com.yuanxin.service.biz.schuserbase.util.SchUserUtil;

import net.jeeshop.core.front.SystemManager;
import net.jeeshop.services.front.account.AccountService;
import net.jeeshop.services.front.account.bean.Account;
import net.jeeshop.services.front.address.AddressService;
import net.jeeshop.services.front.address.bean.Address;
import net.jeeshop.services.front.area.AreaService;
import net.jeeshop.services.front.area.bean.Area;
import net.jeeshop.web.util.SingleLoginUtil;

/**
 * Hello控制器。
 * 
 */
@Controller
@RequestMapping(value = "/phone/address")
public class AddressController {

	private static final org.slf4j.Logger LOG =  LoggerFactory.getLogger(AddressController.class);
	
	@Resource
	private AccountService accountService;
	
	@Resource
	private SingleLoginUtil singleLoginUtil;
	
	@Resource
	private AddressService addressService;
	
	@Resource
	private AreaService areaService;

    @RequestMapping(value = "/index", method = { RequestMethod.GET, RequestMethod.POST })
    public String address(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "收货地址管理");
        String token = request.getParameter("token");
        Account e = singleLoginUtil.singleLogin(token);
        
        String headFlag = request.getParameter("headFlag");
        if(!StringUtils.isBlank(headFlag) && "yes".equals(headFlag)){
        	model.addAttribute("headFlag", "true");
        }else{
        	model.addAttribute("headFlag", "false");
        }
        if(null != e && StringUtils.isNotBlank(e.getAccount())) {
        	String account = e.getAccount();
        	Address address = new Address();
        	address.setAccount(account);
        	List<Address> list = addressService.selectList(address);
        	model.addAttribute("addressList", list);
        } else {
        	model.addAttribute("addressList", new ArrayList<Address>());
        }
        model.addAttribute("token", token);
        return "phone/address/index";
    }
    
    @RequestMapping(value = "/add", method = { RequestMethod.GET, RequestMethod.POST })
    public String add(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	//convertArea();
    	String token = request.getParameter("token");
        Account e = singleLoginUtil.singleLogin(token);
        if(null != e && StringUtils.isNotBlank(e.getAccount())) {
        	Map<String, Area> areaMap = SystemManager.getInstance().getAreaMap();
        	Collection<Area> allAreas =  areaMap.values();
        	List<Area> provinces = new ArrayList<Area>();
        	List<Area> cities = new ArrayList<Area>();
        	List<Area> areas = new ArrayList<Area>();
        	for (Area province : allAreas) {
        		provinces.add(province);
        		List<Area> list = areaMap.get(province.getCode()).getChildren();
        		for (Area city : list) {
        			areas.addAll(city.getChildren());
        		}
        		cities.addAll(list);
        	}
        	model.addAttribute("allAreas", allAreas);
        	model.addAttribute("provinces", provinces);
        	model.addAttribute("cities", cities);
        	model.addAttribute("areas", areas);
        	model.addAttribute("address", new Address());
        	model.addAttribute("account", e);
        } else {
        	model.addAttribute("allAreas", new ArrayList<Area>());
        	model.addAttribute("provinces",  new ArrayList<Area>());
        	model.addAttribute("cities",  new ArrayList<Area>());
        	model.addAttribute("areas",  new ArrayList<Area>());
        	model.addAttribute("address", new Address());
        	model.addAttribute("account", new Account());
        }
        model.addAttribute("token", token);
        return "phone/address/add";
    }
    
    @RequestMapping(value = "/edit", method = { RequestMethod.GET, RequestMethod.POST })
    public String edit(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String id = request.getParameter("id");
        Address address = new Address();
        String pcadetil = "";
    	if(StringUtils.isNotBlank(id)) {
    		address = addressService.selectById(id);
    		if(null != address) {
    			pcadetil = address.getPcadetail();
    		}
    	}
        model.addAttribute("address", address);
        if(StringUtils.isNotBlank(pcadetil)) {
        	String[] pca = pcadetil.split(" ");
        	if(pca.length == 3) {
        		model.addAttribute("shengshi", pca[0] + " " + pca[1]);
        		model.addAttribute("quxian", pca[2]);
        	} else {
        		model.addAttribute("shengshi", null);
        		model.addAttribute("quxian", null);
        	}
        } else {
        	model.addAttribute("shengshi", null);
    		model.addAttribute("quxian", null);
        }
        return "phone/address/edit";
    }
    
    /**
     * 设置默认地址
     * @param model
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "/default", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object isDefault(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
        String id = request.getParameter("id");
        Map<String,Object> jsObject = new HashMap<String, Object>();
        if(StringUtils.isBlank(id)) {
        	jsObject.put("success", false);
        	jsObject.put("msg", "默认地址ID不能为空");
        }
        String token = request.getParameter("token");
        Account e = singleLoginUtil.singleLogin(token);
        if(null != e && StringUtils.isNotBlank(e.getAccount())) {
        	Address address = new Address();
    		address.setId(id);
    		address.setIsdefault("y");
    		address.setAccount(e.getAccount());
    		addressService.setAddressDefault(address);
    		jsObject.put("success", true);
        	jsObject.put("msg", "默认地址设置成功");
        } else {
        	jsObject.put("success", false);
        	jsObject.put("msg", "获取用户登录信息失败");
        }
        return jsObject;
    }
    
    @RequestMapping(value = "/choose", method = { RequestMethod.GET, RequestMethod.POST })
    public String choose(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String token = request.getParameter("token");
    	String addressId= request.getParameter("addressId");
        //Account e = singleLoginUtil.singleLogin(token);
    	Account e = new Account();
    	if(StringUtils.isNotBlank(token)){
    		OrganMemberEntityAO om = SchUserUtil.getOrganMemberEntityAO(token);
    		if(om != null){
    			String baseUserId = om.getId();
            	Account acc = new Account();
            	acc.setBaseuserid(baseUserId);
            	e = accountService.selectOne(acc);
    		}
    	}
        if(null != e && StringUtils.isNotBlank(e.getAccount())) {
        	String account = e.getAccount();
        	Address address = new Address();
        	address.setAccount(account);
        	List<Address> list = addressService.selectList(address);
        	model.addAttribute("addressList", list);
        } else {
        	model.addAttribute("addressList", new ArrayList<Address>());
        }
        model.addAttribute("addressId",addressId);
        model.addAttribute("token",token);
        return "phone/address/choose";
    }
    
    @RequestMapping(value = "/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object delete(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String id = request.getParameter("id");
    	   Map<String,Object> jsObject = new HashMap<String, Object>();
    	if(StringUtils.isNotBlank(id)) {
    		Address add = new Address();
    		add.setId(id);
    		int i = addressService.delete(add);
    		if(i > 0) {
	        	jsObject.put("success", true);
	        	jsObject.put("msg", "收货地址删除成功");
    		}
    	} else {
    		jsObject.put("success", false);
        	jsObject.put("msg", "收货地址删除失败，id为空");
        }
        return jsObject;
    }
    
    @RequestMapping(value = "/save", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object save(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
        Address add = new Address();
        Map<String,Object> jsObject = new HashMap<String, Object>();
        String id = request.getParameter("id");
        String account = request.getParameter("account");
        String name = request.getParameter("name");
        String mobile = request.getParameter("mobile");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("area");
        String shengshi = request.getParameter("shengshi");
        String quxian = request.getParameter("quxian");
        String address = request.getParameter("address");
//        String[] pc = shengshi.split(" ");
//        Area temp = new Area();
//        if(pc.length == 2) {
//        	temp.setName(pc[0]);
//        	Area p = areaService.selectOne(temp);
//        	if(p != null) {
//        		province = p.getCode();
//            	temp.setName(pc[1]);
//            	temp.setPcode(province);
//            	Area c = areaService.selectOne(temp);
//            	if(c != null) {
//            		city = c.getCode();
//            	}
//        	}
//        	
//        }
//        if(StringUtils.isNotBlank(quxian)) {
//        	temp.setName(quxian);
//        	temp.setPcode(city);
//        	Area a = areaService.selectOne(temp);
//        	if(a != null){
//        		area = a.getCode();
//        	}
//        }
        String[] pc = shengshi.split(" ");
        if(pc.length == 2) {
        	province = pc[0];
        	city = pc[1];
        }
        area = quxian;
        if(StringUtils.isNotBlank(id)) {
        	add = addressService.selectById(id);
            add.setAddress(address);
            add.setArea(area);
            add.setCity(city);
            add.setProvince(province);
            add.setMobile(mobile);
            add.setName(name);
            add.setPcadetail(shengshi.replaceAll(",", " ") + " " + quxian);
            int i =addressService.update(add);
    		if(i > 0) {
    			jsObject.put("success", true);
            	jsObject.put("msg", "收货地址保存成功");
    		} else {
    			jsObject.put("success", false);
            	jsObject.put("msg", "收货地址保存失败");
    		}
        } else {
        	add.setAccount(account);
            add.setAddress(address);
            add.setArea(area);
            add.setCity(city);
            add.setProvince(province);
            add.setMobile(mobile);
            add.setName(name);
            add.setPcadetail(shengshi.replaceAll(",", " ") + " " + quxian);
    		int i =addressService.insert(add);
    		if(i > 0) {
    			jsObject.put("success", true);
            	jsObject.put("msg", "收货地址保存成功");
    		} else {
    			jsObject.put("success", false);
            	jsObject.put("msg", "收货地址保存失败");
    		}
        }
        return jsObject;
    }
    
    @RequestMapping(value = "/areas", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object areas(@PathVariable String pcode,Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	Map<String,Object> jsObject = new HashMap<String, Object>();
    	if(StringUtils.isBlank(pcode)) {
    		pcode = "0";
    	}
    	Area area = new Area();
    	area.setPcode(pcode);
    	List<Area> list = areaService.selectList(area);
    	if(null != list && list.size() > 0) {
    		jsObject.put("areas", list);
    	}
    	return jsObject;
    } 
}
